package com.yx.front.utils;

import com.alibaba.fastjson.JSON;
import com.yx.front.model.SysUser;
import com.yx.front.security.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author YangXiong
 */
@Component
@Slf4j
public class LoginUtil {
    @Resource
    private RedisTemplate<String, String> redisTemplate;

    public SysUser getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        log.info("authentication=={}",authentication);
        LoginUser  loginUser;
        try {
            loginUser = (LoginUser) authentication.getPrincipal();
        } catch (Exception e) {
            return null;
        }
        String s = redisTemplate.opsForValue().get("login:"+ loginUser.getSysUser().getId());
        LoginUser sysUser = JSON.parseObject(s, LoginUser.class);
        if (Objects.nonNull(sysUser)) {
            return sysUser.getSysUser();
        }
        return null;
    }
}
